<script setup>
  import { ref,onMounted } from 'vue';
  import { getDeviceList, deleteDeviceInfo } from '@/api/DevConnection';
  import { message } from "@/utils/message";
  import { ElMessageBox } from 'element-plus';
  import AddDialogTable from './components/AddDialogTable.vue';
  import ProtocolConfigDrawer from './components/ProtocolConfigDrawer.vue';
  import CollectSettingDrawer from './components/CollectSettingDrawer.vue';

  onMounted(() => {
    getApiTableDataList();
  });

  // 协议配置
  const protocolConfigDrawer = ref(false);
  const devClickProtocolConfig = () => {
    if (!devVarTableSelectedId.value) {
      message('请先选择需要配置的资源', { type: 'warning' })
      return;
    }
    protocolConfigDrawer.value = true;
  };
  // 协议配置抽屉关闭子组件传值
  const childProtocolDrawerChange = (val) => {
    protocolConfigDrawer.value = val;
  };

  // 采集设置
  const collectSettingDrawer = ref(false);
  const devClickCollectSetting = () => {
    if (!devVarTableSelectedId.value) {
      message('请先选择需要配置的资源', { type: 'warning' })
      return;
    }
    collectSettingDrawer.value = true;
  };
  // 采集设置抽屉关闭子组件传值
  const childCollectDrawerChange = (val) => {
    collectSettingDrawer.value = val;
  };

  // 添加按钮,添加设备、产品、服务
  const dialogVisible = ref(false)
  const devClickAdd = () => {
    dialogVisible.value = true;
  };

  // 添加资源完成,重新请求资源列表
  const childDialogChange = (obj) => {
    dialogVisible.value = obj.value;
    if (obj.type === 'success') {
      getApiTableDataList();
    }
  };

  // 获取设备、产品、服务列表
  const devVarArrTableData = ref([
    {
      type: '',
      fitNum: '',
      itemList: [],
      fitList: []
    },
    {
      type: '',
      fitNum: '',
      itemList: [],
      fitList: []
    },
    {
      type: '',
      fitNum: '',
      itemList: [],
      fitList: []
    }
  ]),
  selectedItemKeys = ref([]);
  const getApiTableDataList = () => {
    getDeviceList().then(res => {
      if (res.status === 200) {
        selectedItemKeys.value = res.data;
        devVarArrTableData.value = [
          {
            type: '',
            fitNum: '',
            itemList: [],
            fitList: []
          },
          {
            type: '',
            fitNum: '',
            itemList: [],
            fitList: []
          },
          {
            type: '',
            fitNum: '',
            itemList: [],
            fitList: []
          }
        ];
        for (let i = 0; i < res.data.length; i++) {
          if (res.data[i].deviceType === '设备' /*&& res.data[i].isDeleted === 0*/) {
            // devVarObjTableData.value.equipment.push(res.data[i])
            devVarArrTableData.value[0].type = res.data[i].deviceType;
            devVarArrTableData.value[0].itemList.push(res.data[i]);
            if (res.data[i].state === 1) {
              devVarArrTableData.value[0].fitList.push(res.data[i]);
            }
          } else if (res.data[i].deviceType === '产品' /*&& res.data[i].isDeleted === 0*/) {
            // devVarObjTableData.value.service.push(res.data[i])
            devVarArrTableData.value[1].type = res.data[i].deviceType;
            devVarArrTableData.value[1].itemList.push(res.data[i]);
            if (res.data[i].state === 1) {
              devVarArrTableData.value[1].fitList.push(res.data[i]);
            }
          } else if (res.data[i].deviceType === '服务' /*&& res.data[i].isDeleted === 0*/) {
            // devVarObjTableData.value.production.push(res.data[i])
            devVarArrTableData.value[2].type = res.data[i].deviceType;
            devVarArrTableData.value[2].itemList.push(res.data[i]);
            if (res.data[i].state === 1) {
              devVarArrTableData.value[2].fitList.push(res.data[i]);
            }
          }
          if (devVarTableSelectedId.value === res.data[i].id) {
            devVarTableSelectedItem.value = res.data[i];
          }
        }
      } else {
        message(res.message, { type: 'error' })
      }
    }).catch(err => {
      console.log(err)
    })
  };

  // 鼠标点击选中设备、产品、服务以后高亮
  const devVarCollectDisabled = ref(false),
    devVarTableSelectedId = ref(null),
    devVarTableSelectedItem = ref(null);
  const devClickTableSelected = (item) => {
    if (devVarTableSelectedId.value && devVarTableSelectedId.value === item.id) {
      devVarTableSelectedId.value = null;
      devVarTableSelectedItem.value = null;
    } else {
      devVarTableSelectedId.value = item.id;
      devVarTableSelectedItem.value = item;
    }
    if (item.state === 0) {
      devVarCollectDisabled.value = true;
    } else {
      devVarCollectDisabled.value = false;
    }

    // this.id = selectedItem.id
    // this.deviceType = selectedItem.deviceType
    // this.dev_name = selectedItem.deviceName
    // this.NetId= selectedItem.gatewayId
    // this.port = selectedItem.connector
    // this.getway_id = selectedItem.protocol
    // this.slaveAddress1 = selectedItem.passiveAddress
    // this.slaveip = selectedItem.passiveIp
    // this.portid = selectedItem.passivePort
    // this.m_type  =  selectedItem.protocolType
    // this.addr =  selectedItem.protocolAddress
    // this.num = selectedItem.protocolNumber
    // this.tar_addr = selectedItem.targetAddress
    // this.tar_port = selectedItem.targetPort
    // this.device_account = selectedItem.deviceAccount
    // this.device_pwd = selectedItem.devicePassword
    // this.clientId = selectedItem.clientId
    // this.sub_topic = selectedItem.subscribeTopic
    // this.issue_topic = selectedItem.releaseTopic
    // this.qos = selectedItem.qos
    // this.cls = selectedItem.clearSession
    // this.URL = selectedItem.url
    // this.securityPolicy = selectedItem.securityPolicy
    // this.file = selectedItem.nodePath
    // this.password = selectedItem.certificates
    // this.dataReading = selectedItem.readingMethod
    // this.timeout = selectedItem.timeoutSetting
    // this.RSbaud =selectedItem.baudRate
    // this.RSdataBit = selectedItem.dataBit
    // this.RSstopBit = selectedItem.stopBit
    // this.RSschool = selectedItem.verify
    // this.CANZformat = selectedItem.frameFormat
    // this.CANZtype =  selectedItem.frameType
    // this.CANZid = selectedItem.frameId
    // this.WIFIid = selectedItem.wifiAccount
    // this.WIFIpassword = selectedItem.wifiPassword
  }

  // 删除设备、产品、服务
  const devClickTableDelete = (item) => {
    ElMessageBox.confirm('确定要删除吗?',{ type: 'warning',}).then(() => {
      deleteDeviceInfo({id: item.id}).then(res => {
        if (res.status === 200) {
          getApiTableDataList();
          message('删除成功！', { type: 'success' });
        } else {
          message(res.message, { type: 'error' });
        }
      }).catch(err => {
        console.log(err);
      })
    }).catch(() => {
      // catch error
    })
  }
</script>

<template>
  <div class="dev-wrapper">
    <div class="dev-header">
      <div class="dev-header-left">
        <el-button @click="devClickProtocolConfig">协议配置</el-button>
        <el-button @click="devClickCollectSetting" :disabled="devVarCollectDisabled">采集设置</el-button>
      </div>
      <el-button type="primary" @click="devClickAdd">添  加</el-button>
    </div>
    <div class="dev-body-main">
      <!-- 设备、产品、服务 -->
      <div class="dev-body-item" v-for="tableList in devVarArrTableData" :key="tableList">
        <div class="dev-body-title">
          <h3 class="dev-body-text">{{ tableList.type }}</h3>
          <span class="dev-body-tips">接入{{ tableList.itemList.length }}个，适配{{ tableList.fitList.length }}个</span>
        </div>
        <div class="dev-body-table">
          <div class="table-block-box"
            v-for="item in tableList.itemList"
            :key="item"
            :class="[
              item.id === devVarTableSelectedId ? 'table-selected-active' : '',
              item.state === 1 ? 'table-shadow-green' : '',
              item.state === 0 ? 'table-shadow-red' : '',
            ]"
          >
            <div class="table-block" @click="devClickTableSelected(item)">
              <div class="table-block-title">
                <div class="table-block-text">{{ item.deviceName }}</div>
                <el-button class="table-block-del" link type="primary" @click.stop="devClickTableDelete(item)">删除</el-button>
              </div>
              <div class="table-block-status">设备状态：{{ item.state === 0 ? '未适配' : '已适配' }}</div>
              <div class="table-block-id">网关ID:{{ item.gatewayId }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 协议配置 -->
    <ProtocolConfigDrawer
      :protocolConfig-drawer="protocolConfigDrawer"
      :devVarTableSelected-item="devVarTableSelectedItem"
      @childProtocolDrawer="childProtocolDrawerChange"
      @childGetApiTableDataList="getApiTableDataList"
    ></ProtocolConfigDrawer>
    <!-- 采集设置 -->
    <CollectSettingDrawer
      :collectSetting-drawer="collectSettingDrawer"
      :devVarTableSelected-item="devVarTableSelectedItem"
      @childCollectDrawer="childCollectDrawerChange"
    ></CollectSettingDrawer>
    <!-- 添加资源设备、产品、服务 -->
    <AddDialogTable
      :dialog-visible="dialogVisible"
      :selected-itemKeys="selectedItemKeys"
      @childDialogVisible="childDialogChange"
    ></AddDialogTable>
  </div>
</template>

<style lang="scss" scoped>
  .dev-wrapper {
    width: 100%;
    height: 100%;
    font-size: 16px;
    font-weight: 500;
    border-radius: 10px;
    box-shadow: 2px 2px 2px 1px rgba(0, 0, 0, 0.2);
    background-color: #fff;

    .dev-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 15px 10px 10px;
    }

    .dev-body-main {
      .dev-body-item {
        width: 100%;
        /* height: calc(30% - 30px); */
        .dev-body-title {
          .dev-body-text {
            display: inline-block;
            padding: 0 15px;
          }
        }

        .dev-body-table {
          width: 100%;
          max-height: 232px;
          display: flex;
          /* height: calc(100% - 30px); */
          flex-wrap: wrap;
          overflow: auto;
          margin-top: 10px;

          .table-block-box {
            width: 270px;
            /* height: 140px; */
            border-right: 1px solid #ccc;
            background-color: #fff;
            border-radius: 10px;
            margin: 10px;
            flex-basis: calc(20% - 20px);
            vertical-align: top;

            .table-block {
              padding-left: 20px;
              border-radius: 10px;
              box-shadow: 2px 2px 2px 2px rgba(0, 0, 0, 0.2);

              .table-block-title {
                display: flex;
                justify-content: space-between;
                padding: 10px 20px 0 0;

                .table-block-text {
                  display: inline-block;
                  font-weight: 700;
                }
              }

              .table-block-status {
                margin: 6px 0;
                font-size: 14px;
                color: gray;
              }

              .table-block-id {
                font-size: 14px;
                color: gray;
                padding-bottom: 8px;
              }
            }
          }

          .table-selected-active {
            background-color: #efecec;
            cursor: pointer;
            /* 设置鼠标样式为手型 */
          }

          .table-shadow-green {
            box-shadow: 0px -9px 1px -3px #6fc444;
          }

          .table-shadow-red {
            box-shadow: 0px -9px 1px -3px red;
          }
        }
      }
    }
  }
</style>
